package init

import (
	"fmt"
	"github.com/go-redis/redis"
	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"monthly-test/global"
	"monthly-test/internal/model/dao"
	"sync"
)

func init() {
	InitConfig()
	InitDB()
	InitRdb()
}

func InitConfig() {
	viper.SetConfigFile("D:\\goWork\\homework\\monthly-test\\dev.yaml")
	err := viper.ReadInConfig()
	if err != nil {
		panic(err)
	}
	viper.Unmarshal(&global.GlobalConfig)
	fmt.Println(global.GlobalConfig)
}

var once sync.Once

func InitDB() {
	var err error
	config := global.GlobalConfig.Mysql
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=True", config.User, config.Password, config.Host, config.Port, config.Database)
	once.Do(func() {
		global.DB, err = gorm.Open(mysql.Open(dsn))
		if err != nil {
			panic(err)
		}
	})
	fmt.Println("MYSQL连接成功")
	global.DB.AutoMigrate(&dao.User{}, &dao.Friend{}, &dao.Group{}, &dao.GroupMember{}, &dao.Video{})
}
func InitRdb() {
	global.Rdb = redis.NewClient(&redis.Options{
		Addr:     global.GlobalConfig.Redis.Host,
		Password: global.GlobalConfig.Redis.Password,
		DB:       0,
	})
	err := global.Rdb.Ping().Err()
	if err != nil {
		panic(err)
	}
	fmt.Println("Redis连接成功")

}
